const http=require('http');
const fs=require('fs');
const mysql=require('mysql');
const io=require('socket.io');
const url=require('url');

let db=mysql.createPool({host:'localhost',user:'root',database:'20180326'});


let httpServer=http.createServer((req,res)=>{
    let {pathname,query}=url.parse(req.url,true)
    fs.readFile(`www${pathname}`,(err,data)=>{
        if(err){
            res.writeHeader(404);
            res.write('NOT FOUND');
        }else{
            res.write(data);
        }
        res.end();
    })
});

let wsServer=io.listen(httpServer);

wsServer.on('connection',sock=>{
    sock.on('logup',(username,password)=>{
        if(!/^\w{6,32}/.test(username)){
            sock.emit('logup-ren',1,'用户名格式错误')
        }else if(!/^.{6,32}/.test(password)){
            sock.emit('logup-ren',1,'密码格式错误')
        }else{
            db.query(`SELECT id FROM user_table WHERE username='${username}'`,(err,data)=>{
                if(err){
                    sock.emit('logup-ren',1,'数据库错误')
                }else if(data.length>0){
                    sock.emit('logup-ren',1,'该用户名已经注册')
                }else{
                    db.query(`INSERT INTO user_table (username,password,online) VALUES('${username}','${password}',1)`,err=>{
                        if(err){
                            sock.emit('logup-ren',1,'数据库错误')
                        }else{
                            sock.emit('logup-ren',0,'注册成功')
                        }
                    })
                }
            })
        }
    })
    sock.on('login',(username,password)=>{
        if(!/^\w{6,32}$/.test(username)){
            sock.emit('login-ren',1,'用户名格式错误')
        }else if(!/^.{6,32}$/.test(password)){
            sock.emit('login-ren',1,'密码格式错误')
        }else{
            db.query(`SELECT id,password FROM user_table WHERE username='${username}'`,(err,data)=>{
                if(err){
                    sock.emit('login-ren',1,'数据库错误')
                }else if(data[0].password!=password){
                    sock.emit('login-ren',1,'密码错误')
                }else{
                    db.query(`UPDATE user_table SET online=1 WHERE id=${data[0].id}`,err=>{
                        if(err){
                            sock.emit('login-ren',1,'服务器错误')
                        }else{
                             sock.emit('login-ren',0,'登录成功')
                        }
                    })
                }
            })
        }
    })
})


httpServer.listen(8080);
